package site.marqstree.smartbutler.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.fragment.app.Fragment;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import site.marqstree.smartbutler.R;
import site.marqstree.smartbutler.adapter.WeChatAdapter;
import site.marqstree.smartbutler.entity.WeChatData;
import site.marqstree.smartbutler.ui.WebViewActivity;
import site.marqstree.smartbutler.util.L;
import site.marqstree.smartbutler.util.StaticClass;

/*
 * 项目名: SmartButler
 * 包名: site.marqstree.smartbutler.fragment
 * 文件名: WechatFragment
 * 创建者: marqstree
 * 创建时间: 2019/12/27 14:22
 * 描述: 微信精选
 */
public class WechatFragment extends Fragment {

    //ButterKnife解绑对象
    private Unbinder mUnbinder;

    private ListView mListView;
    private List<WeChatData> mList = new ArrayList<>();
    //标题
    private List<String> mListTitle = new ArrayList<>();
    //地址
    private List<String> mListUrl = new ArrayList<>();

    //1.将布局文件fragment_tab转换为View
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wechat, null);
        findView(view);
        //获取ButterKnife解绑对象
        mUnbinder = ButterKnife.bind(WechatFragment.this, view);
        return view;
    }


    //初始化View
    private void findView(View view) {
        mListView = (ListView) view.findViewById(R.id.mListView);

        //解析接口
        String url = "http://v.juhe.cn/weixin/query?key=" + StaticClass.WECHAT_KEY + "&ps=100";
        RxVolley.get(url, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                //Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
                L.i("wechat json:" + t);
                parsingJson(t);
            }
        });

        //点击事件
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                L.i("position:" + position);
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("title", mListTitle.get(position));
                intent.putExtra("url", mListUrl.get(position));
                startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解除ButterKnife绑定
        mUnbinder.unbind();
    }

    //供外部调用，生成TabFragment实例，而不是new方式
    //此方法：采用Bundle模式，传入参数
    // 1）采用Bundle模式的好处：
    // 在用户中断操作，应用被系统放置在后台运行，系统自动保存Bundle，
    // 此Fragment可能会被系统销毁
    //当用户切换回此Fragment时，系统会自动调用onCreate方法，恢复自动保存的Bundle
    // 2）采用new方式创建Fragment不会自动恢复参数，导致Fragment中的数据丢失，界面空白。
    public static WechatFragment newInstance() {
        WechatFragment wechatFragment = new WechatFragment();
        return wechatFragment;
    }

    //解析Json
    private void parsingJson(String t) {
        try {
            JSONObject jsonObject = new JSONObject(t);
            JSONObject jsonresult = jsonObject.getJSONObject("result");
            JSONArray jsonList = jsonresult.getJSONArray("list");
            for (int i = 0; i < jsonList.length(); i++) {
                JSONObject json = (JSONObject) jsonList.get(i);
                WeChatData data = new WeChatData();

                String titlr = json.getString("title");
                String url = json.getString("url");

                data.setTitle(titlr);
                data.setSource(json.getString("source"));
                if(TextUtils.isEmpty(json.getString("firstImg").trim()))
                    data.setImgUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1578217477883&di=8379bf84733e2d017f8e2288e51297cd&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F24%2F90%2F31300543319869144765908602532.jpg");
                else
                    data.setImgUrl(json.getString("firstImg"));

                mList.add(data);

                mListTitle.add(titlr);
                mListUrl.add(url);
            }
            WeChatAdapter adapter = new WeChatAdapter(getActivity(), mList);
            mListView.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}